Passed
Pull Request — filestream (#169)
by
unknown
01:48
created

write.ts ➔ writeAsync   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
1
import { WriteTags } from "../types/Tags"
2
import { WriteCallback } from "../types/write"
3
import { create }  from "./create"
4
import { removeTagsFromBuffer } from "./remove"
5
import { isFunction, isString, validateString } from "../util"
6
import { writeId3TagToFileAsync, writeId3TagToFileSync } from "../file-write"
7
8
/**
9
 * Replaces any existing tags with the given tags in the given buffer.
10
 * Throws in case of error.
11
 * @public
12
 */
13
export function write(tags: WriteTags, buffer: Buffer): Buffer
14
15
/**
16
 * Replaces synchronously any existing tags with the given tags in the
17
 * specified file.
18
 * Throws in case of error.
19
 * @public
20
 */
21
export function write(tags: WriteTags, filepath: string): void
22
23
/**
24
 * Replaces asynchronously any existing tags with the given tags in the
25
 * specified file.
26
 * @public
27
 */
28
export function write(
29
    tags: WriteTags, filepath: string, callback: WriteCallback
30
): void
31
32
export function write(
33
    tags: WriteTags,
34
    filebuffer: string | Buffer,
35
    callback?: WriteCallback
36
): Buffer | void {
37
    const id3Tag = create(tags)
38
39
    if (isFunction(callback)) {
40
        writeId3TagToFileAsync(validateString(filebuffer), id3Tag)
41
        .then(() => callback(null), (error) => callback(error))
42
        return
43
    }
44
    if (isString(filebuffer)) {
45
        return writeId3TagToFileSync(filebuffer, id3Tag)
46
    }
47
    return writeInBuffer(id3Tag, filebuffer)
48
}
49
50
function writeInBuffer(tags: Buffer, buffer: Buffer) {
51
    buffer = removeTagsFromBuffer(buffer) || buffer
52
    return Buffer.concat([tags, buffer])
53
}
54